/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.teamx.ets.distSchedule;

import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.ace.ability.AceAbility;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;
import java.util.Objects;

public class AddDeviceAbility extends AceAbility {

    static final HiLogLabel LABEL = new HiLogLabel(3, 0xD000F00, "NFC");

    @Override
    public void onStart(Intent intent) {
        setInstanceName("addDevice");
        IntentParams intentParams = intent.getParams();
        if (intentParams != null) {
            String paramsFormJS = (String) intent.getParams().getParam("__startParams");
            // 无感配网模块netconfig跳转回来
            if (paramsFormJS != null) {
                ZSONObject zsonObject = ZSONObject.stringToZSON(paramsFormJS);
                String deviceId = (String) zsonObject.get("deviceId");
                if (deviceId != null) {
                    intentParams.setParam("deviceId", deviceId);
                    String url = "pages/index";
                    setPageParams(url, intentParams);
                }
            }
            else {
                    String sessionId = intent.getStringParam("nanSessionId");
                    intentParams.setParam("data91", getNfcInfo(intent));
                    intentParams.setParam("nanSessionId", sessionId);
                    String url = "pages/index";
                    setPageParams(url, intentParams);
            }
        }
        super.onStart(intent);
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    /**
     * 获取nfc数据
     */
    private String getNfcInfo(Intent intent) {
        String data91 = "";
        Object businessInfo = Objects.requireNonNull(intent.getParams()).getParam("businessInfo");
        if (businessInfo != null) {
            ZSONObject businessInfoZSON = ZSONObject.classToZSON(businessInfo);
            // data91 is your device sn in nfc tag.
            try {
                data91 = businessInfoZSON.getZSONObject("params").getString("91");
                HiLog.info(LABEL, "======data91===" + data91);
            } catch (Exception e) {
                HiLog.info(LABEL, "=====NFC自定义数据解析错误，请对照profile自行检查");

            }
        }
        return data91;
    }
}
